package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.AddressMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Address;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.AddressService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 收货地址Service实现类
 */
@Slf4j
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> getAddressList(Long userId) {
        if (userId == null) {
            return List.of();
        }

        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, userId);
        wrapper.orderByDesc(Address::getIsDefault);
        wrapper.orderByDesc(Address::getCreateTime);
        return addressMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public Address addAddress(Long userId, Address address) {
        if (userId == null || address == null) {
            throw new IllegalArgumentException("参数不完整");
        }

        address.setUserId(userId);
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());

        // 如果是第一个地址，自动设为默认地址
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, userId);
        long count = addressMapper.selectCount(wrapper);
        if (count == 0) {
            address.setIsDefault(1);
        } else {
            address.setIsDefault(0);
        }

        addressMapper.insert(address);
        return address;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean updateAddress(Long addressId, Long userId, Address address) {
        if (addressId == null || userId == null || address == null) {
            return false;
        }

        // 验证地址所有权
        Address existingAddress = addressMapper.selectById(addressId);
        if (existingAddress == null || !existingAddress.getUserId().equals(userId)) {
            throw new IllegalArgumentException("地址不存在或无权操作");
        }

        address.setId(addressId);
        address.setUserId(userId);
        address.setUpdateTime(LocalDateTime.now());
        // 保持默认地址状态不变
        address.setIsDefault(existingAddress.getIsDefault());

        int result = addressMapper.updateById(address);
        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean deleteAddress(Long addressId, Long userId) {
        if (addressId == null || userId == null) {
            return false;
        }

        // 验证地址所有权
        Address address = addressMapper.selectById(addressId);
        if (address == null || !address.getUserId().equals(userId)) {
            throw new IllegalArgumentException("地址不存在或无权操作");
        }

        int result = addressMapper.deleteById(addressId);

        // 如果删除的是默认地址，将第一个地址设为默认
        if (result > 0 && address.getIsDefault() == 1) {
            LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Address::getUserId, userId);
            wrapper.orderByDesc(Address::getCreateTime);
            wrapper.last("LIMIT 1");
            Address firstAddress = addressMapper.selectOne(wrapper);
            if (firstAddress != null) {
                firstAddress.setIsDefault(1);
                addressMapper.updateById(firstAddress);
            }
        }

        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean setDefaultAddress(Long addressId, Long userId) {
        if (addressId == null || userId == null) {
            return false;
        }

        // 验证地址所有权
        Address address = addressMapper.selectById(addressId);
        if (address == null || !address.getUserId().equals(userId)) {
            throw new IllegalArgumentException("地址不存在或无权操作");
        }

        // 将该用户的所有地址设为非默认
        LambdaUpdateWrapper<Address> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Address::getUserId, userId);
        updateWrapper.set(Address::getIsDefault, 0);
        addressMapper.update(null, updateWrapper);

        // 将指定地址设为默认
        address.setIsDefault(1);
        address.setUpdateTime(LocalDateTime.now());
        int result = addressMapper.updateById(address);
        return result > 0;
    }

    @Override
    public Address getDefaultAddress(Long userId) {
        if (userId == null) {
            return null;
        }

        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, userId);
        wrapper.eq(Address::getIsDefault, 1);
        return addressMapper.selectOne(wrapper);
    }
}
